package com.cool.springcloud.config;

import com.cool.springcloud.myselfloadbalancer.DefineMyselfLoadBalancer;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.loadbalancer.core.RandomLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;

/**
 * 切换 负载均衡算法
 *
 *
 * @Author ifredomvip@gmail.com
 * @Date 2022/8/25 16:20
 * @Version 1.0.0
 * @Description
 **/
public class CustomLoadBalancerConfiguration{

    /**
     * 随机负载均衡器
     * 同一时间只能存在一个
     */
//        @Bean
    ReactorLoadBalancer<ServiceInstance> randomLoadBalancer(Environment environment,
                                                            LoadBalancerClientFactory loadBalancerClientFactory) {
        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
        System.out.println("================触发随机负载均衡================");
        return new RandomLoadBalancer(loadBalancerClientFactory
                .getLazyProvider(name, ServiceInstanceListSupplier.class),
                name);
    }

    /**
     * 自己实现的负载均衡器
     *
     */
    @Bean
    ReactorLoadBalancer<ServiceInstance> myselfLoadBalancer(Environment environment,
                                                            LoadBalancerClientFactory loadBalancerClientFactory) {
        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
        System.out.println("================自定义负载均衡================");
        return new DefineMyselfLoadBalancer(loadBalancerClientFactory
                .getLazyProvider(name, ServiceInstanceListSupplier.class),
                name);
    }
}

